<template>
  <div class="announcement-form-container">
    <el-card class="form-card" shadow="hover">
      <div class="card-header">
        <h2 class="form-title">发布新公告</h2>
        <p class="form-subtitle">填写公告信息并发布</p>
      </div>
      
      <el-row :gutter="20" class="form-content">
        <el-form ref="formRef" :model="formData" :rules="rules" size="default" label-width="120px">
          <!-- 公告标题 -->
          <el-col :span="24">
            <el-form-item label="公告标题" prop="noticeTitle">
              <el-input 
                v-model="formData.noticeTitle" 
                type="text" 
                placeholder="请输入公告标题" 
                clearable
                class="modern-input"
              >
                <template #prefix>
                  <el-icon><Document /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          
          <!-- 分类和发布人 -->
          <el-col :span="20">
            <el-form-item label="分类" prop="noticeType">
              <el-select 
                v-model="formData.noticeType" 
                placeholder="请选择分类" 
                clearable 
                class="modern-select"
              >
                <el-option 
                  v-for="(item, index) in noticeType" 
                  :key="index" 
                  :label="item.label"
                  :value="item.value" 
                  :disabled="item.disabled"
                >
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                    {{ item.value }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="20">
            <el-form-item label="发布人" prop="createBy">
              <el-input 
                v-model="formData.createBy" 
                type="text" 
                placeholder="请输入发布人" 
                clearable
                class="modern-input"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          
          <!-- 上传区域 -->
         <el-col :span="24">
    <el-form-item label="附件上传" prop="remark">
      <el-upload 
        ref="uploadRef"
        v-model:file-list="remarkfileList"
    :http-request="customUpload" 
        :before-upload="remarkBeforeUpload"
        class="modern-upload"
        drag
        multiple
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :on-remove="handleRemove"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持上传jpg/png/pdf/doc文件，且不超过2MB
          </div>
        </template>
        <template #file="{ file }">
          <div class="file-item">
            <el-icon class="file-icon"><Document /></el-icon>
            <span class="file-name">{{ file.name }}</span>
            <span class="file-size">({{ formatFileSize(file.size) }})</span>
            <el-progress 
              v-if="file.status === 'uploading'"
              :percentage="file.percentage"
              :stroke-width="2"
              class="upload-progress"
            />
          </div>
        </template>
      </el-upload>
    </el-form-item>
  </el-col>
          
          <!-- 定时发送和时间选择 -->
          <el-col :span="24">
            <el-form-item label="定时发送" prop="status" required>
              <el-switch 
                v-model="formData.status" 
                active-text="启用定时发送"
                inactive-text="立即发送"
                inline-prompt
                :active-icon="Check"
                :inactive-icon="Close"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              />
            </el-form-item>
          </el-col>
          
           <el-col :span="18" v-if="formData.status">
    <el-form-item label="发布时间" prop="updateTime">
      <el-time-picker 
        v-model="formData.updateTime" 
        format="HH:mm:ss" 
        value-format="HH:mm:ss"
        class="modern-time-picker"
        placeholder="请选择发布时间" 
        clearable
      >
        <template #prefix>
          <el-icon><Clock /></el-icon>
        </template>
      </el-time-picker>
    </el-form-item>
  </el-col>
          
          <!-- 公告内容 -->
          <el-col :span="24">
            <el-form-item label="公告内容" prop="noticeContent">
              <el-input 
                v-model="formData.noticeContent" 
                type="textarea" 
                placeholder="请输入公告内容"
                :autosize="{minRows: 4, maxRows: 8}" 
                class="modern-textarea"
                show-word-limit
                maxlength="500"
              />
            </el-form-item>
          </el-col>
          
          <!-- 操作按钮 -->
          <el-col :span="24">
            <el-form-item class="form-actions">
              <el-button 
                type="primary" 
                @click="submitForm" 
                class="submit-btn"
                :icon="Promotion"
              >
                提交公告
              </el-button>
              <el-button 
                @click="resetForm" 
                class="reset-btn"
                :icon="Refresh"
              >
                重置表单
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs } from 'vue'
import { addNotice } from "@/api/fbgg/fbgg"
import dayjs from 'dayjs'

import { 
  ElMessage,
  ElCard,
  ElRow,
  ElCol,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElUpload,
  ElButton,
  ElSwitch,
  ElTimePicker
} from 'element-plus'
import {
  Document,
  User,
  UploadFilled,
  Clock,
  Promotion,
  Refresh,
  Check,
  Close
} from '@element-plus/icons-vue'

const formRef = ref()
const customUpload = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    const formDataObj = new FormData();
    // 添加表单数据
    Object.entries(formData.value).forEach(([key, value]) => {
      if (value !== null) {
        if (key === 'status') {
          // 处理布尔值转数字
          formDataObj.append(key, value ? 1 : 0);
        } else if (key === 'updateTime' && formData.value.status) {
          // 处理定时发送时间
          const currentDate = dayjs().format('YYYY-MM-DD');
          formDataObj.append(key, `${currentDate} ${value}`);
        } else {
          formDataObj.append(key, value);
        }
      }
    });
    // 添加文件数据
    remarkfileList.value.forEach(file => {
      formDataObj.append('remark', file.raw);
    });

    await addNotice(formDataObj);
    ElMessage.success('公告发布成功');
    resetForm();
  } catch (error) {
    ElMessage.error('公告发布失败，请重试');
    console.error('提交表单失败:', error);
  }
}

const uploadRef = ref()
const remarkfileList = ref([])
const remarkAction = ref('https://your-upload-api-endpoint') // 替换为实际的上传接口

// 格式化文件大小显示
const formatFileSize = (size) => {
  if (size < 1024) return size + 'B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + 'KB'
  return (size / (1024 * 1024)).toFixed(1) + 'MB'
}
const handleUploadError = (error, file, fileList) => {
  ElMessage.error(`${file.name} 上传失败: ${error.message}`)
  remarkfileList.value = fileList
}

// 移除文件处理
const handleRemove = (file, fileList) => {
  remarkfileList.value = fileList
  // 更新表单数据中的文件信息
  formData.value.remark = JSON.stringify(fileList.map(f => ({
    name: f.name,
    url: f.response?.url || f.url,
    size: f.size
  })));
}

// 上传成功处理
const handleUploadSuccess = (response, file, fileList) => {
  ElMessage.success(`${file.name} 上传成功`)
  remarkfileList.value = fileList
  // 如果需要将文件信息保存到表单数据中
  formData.value.remark = JSON.stringify(fileList.map(f => ({
    name: f.name,
    url: f.response?.url || f.url,
    size: f.size
  })));
}

const data = reactive({
  formData: {
    status: 0,
    noticeTitle: null,
    noticeType: null,
    createBy: null,
    noticeContent: null,
    updateTime: null,
    remark: null,
  },
  rules: {
    noticeTitle: [{
      required: true,
      message: '请输入公告标题',
      trigger: 'blur'
    }],
    noticeType: [{
      required: true,
      message: '请选择分类',
      trigger: 'change'
    }],
    createBy: [{
      required: true,
      message: '请输入发布人',
      trigger: 'blur'
    }],
    updateTime: [{
      required: true,
      message: '发布时间不能为空',
      trigger: 'change'
    }],
    noticeContent: [{
      required: true,
      message: '请输入公告内容',
      trigger: 'blur'
    }],
  }
})
const { formData, rules } = toRefs(data)

const noticeType = ref([
  { value: 'admin', label: '行政部' },
  { value: 'logistics', label: '后勤部' },
  { value: 'hr', label: '人力资源部' },
  { value: 'finance', label: '财务部' },
  { value: 'it', label: 'IT 部' }
])
/**
 * @name: 处理文件列表变化
 * @description: 文件列表变化时更新 remarkfileList
 * @param {Array} fileList 当前文件列表
 */
function handleFileChange(fileList) {
  remarkfileList.value = fileList;
}

/**
 * @name: 上传之前的文件判断
 * @description: 上传之前的文件判断，判断文件大小文件类型等
 * @param {*} file
 * @return {*}
 */
function remarkBeforeUpload(file) {
  const isRightSize = file.size / 1024 / 1024 < 2
  const isAcceptType = ['image/jpeg', 'image/png', 'application/pdf', 'application/msword'].includes(file.type)
  
  if (!isRightSize) {
    ElMessage.error('文件大小超过 2MB')
    return false
  }
  
  if (!isAcceptType) {
    ElMessage.error('只支持上传jpg/png/pdf/doc文件')
    return false
  }
  
  return isRightSize && isAcceptType
}

/**
 * @name: 表单提交
 * @description: 表单提交方法，调用 addNotice 函数上传表单数据
 * @return {*}
 */
async function submitForm() {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    // 若启用定时发送且选择了时间，补充日期信息
    if (formData.value.status && formData.value.updateTime) {
      const currentDate = dayjs().format('YYYY-MM-DD');
      formData.value.updateTime = `${currentDate} ${formData.value.updateTime}`;
    }
     formData.value.status = formData.value.status ? 1 : 0;
    await addNotice(formData.value);
    ElMessage.success('公告发布成功');
    resetForm();
  } catch (error) {
    ElMessage.error('公告发布失败，请重试');
    console.error('提交表单失败:', error);
  }
}
/**
 * @name: 表单重置
 * @description: 表单重置方法
 * @return {*}
 */
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  remarkfileList.value = [];
  ElMessage.info('表单已重置');
}
</script>

<style scoped>
/* 样式部分保持不变 */
.announcement-form-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.form-card {
  max-width: 1000px;
  margin: 0 auto;
  border-radius: 12px;
  border: none;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(to right, #409EFF, #67C23A);
  color: white;
}

.form-title {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.form-subtitle {
  margin: 8px 0 0;
  font-size: 0.875rem;
  opacity: 0.9;
}

.form-content {
  padding: 24px;
}

.modern-input, .modern-select, .modern-time-picker {
  --el-input-focus-border-color: #409EFF;
  --el-input-hover-border-color: #c0c4cc;
}

.modern-input:deep(.el-input__inner) {
  border-radius: 8px;
  padding-left: 40px;
}

.modern-input:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
  padding-left: 10px;
}

.modern-select:deep(.el-input__inner) {
  border-radius: 8px;
}

.modern-time-picker:deep(.el-input__inner) {
  border-radius: 8px;
  padding-left: 40px;
}

.modern-time-picker:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
  padding-left: 10px;
}

.modern-textarea:deep(.el-textarea__inner) {
  border-radius: 8px;
  resize: vertical;
  min-height: 120px;
}

.modern-upload {
  --el-upload-dragger-padding-horizontal: 20px;
  --el-upload-dragger-padding-vertical: 40px;
}

.modern-upload:deep(.el-upload-dragger) {
  border-radius: 8px;
  border: 2px dashed #dcdfe6;
  background-color: #fafafa;
  transition: all 0.3s;
}

.modern-upload:deep(.el-upload-dragger:hover) {
  border-color: #409EFF;
  background-color: #f0f7ff;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.file-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin: 5px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  transition: all 0.3s;
}

.file-item:hover {
  background-color: #e6f1ff;
}

.file-icon {
  margin-right: 8px;
  color: #409EFF;
}

.file-name {
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  color: #909399;
  font-size: 12px;
}

.upload-progress {
  width: 100px;
  margin-left: 10px;
}

.submit-btn {
  background: linear-gradient(to right, #409EFF, #67C23A);
  border: none;
  border-radius: 8px;
  padding: 10px 24px;
  font-weight: 500;
  transition: all 0.3s;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.reset-btn {
  border-radius: 8px;
  padding: 10px 24px;
  font-weight: 500;
  transition: all 0.3s;
}

.reset-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
}

.el-upload__tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .form-card {
    margin: 0 10px;
  }
  
  .el-col {
    width: 100%;
    padding: 0;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .submit-btn, .reset-btn {
    width: 100%;
  }
}
</style>